﻿using WenAntdUI.Helps;
using WenAntdUI.Pages.Components;
using WenAntdUI.Services;

namespace WenAntdUI.Pages.SysAdmin
{
    [Description("用户管理")]
    public partial class SysUserPage : UserControl
    {
        private UserService userService;
        private string pageCode;

        public SysUserPage()
        {
            this.userService = App.GetService<UserService>();
            InitializeComponent();
            this.adminTable1.SetColumns<SysUser>();
            this.adminTable1.Query();

            this.adminTable1.SaveItemData += AdminTable1_SaveItemData;
            this.adminTable1.CellClick += AdminTable1_CellClick;
        }

        #region 重置属性

        public string PageCode
        {
            get => pageCode;
            set
            {
                pageCode = value;
                if (!string.IsNullOrWhiteSpace(value))
                    this.auth1.SetAuth(this.adminTable1, value);
            }
        }

        #endregion

        #region 私有属性

        private SysUser Selected { get; set; }

        #endregion

        private void AdminTable1_CellClick(object sender, AntdUI.TableClickEventArgs e)
        {
            if (e.Record is SysUser sysUser)
            {
                this.Selected = sysUser;
            }
        }


        private void AdminTable1_SaveItemData(object? sender, Controls.AdminTable.AdminTableItemEventArgs e)
        {
            if (e.IsAdd)
            {
                e.Cancel = true;
                if (e.Item is SysUser user)
                {
                    var result = userService.Insert(user);
                    Msgbox.ShowInfo(result ? "保存成功" : "用户名已经存在");
                }
            }
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            var user = adminTable1.GetSelectedItem() as SysUser;
            if (user is null) return;

            var dia = Msgbox.ShowInput();
            if (dia.Result)
            {
                userService.ResetPassword(user.UserName, dia.Text);
                Msgbox.ShowSuccess("已完成密码重置，请使用新密码登录");
                adminTable1.Query();
            }
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            if (Selected is null) return;
            var fm = App.GetService<UserRoleSelectForm>();
            fm.SetUserRole(Selected.UserName);
            fm.ShowDialog();
        }
    }
}
